import 'package:dio/dio.dart';
import 'extra_keys.dart';

class ToastInterceptor extends Interceptor {
  Function? _loadingFunc;

  // // 用于测试网络请求时长
  // DateTime? start;

  @override
  void onError(
    DioError err,
    ErrorInterceptorHandler handler,
  ) {
    if (_loadingFunc != null) _loadingFunc!.call();
    // print("****** 请求异常(Error) ******");
    // // 用于测试网络请求时长
    // final Duration diff = DateTime.now().difference(start!);
    // print('request time : $diff');
    // 当需要toast时, 弹出错误提示
    if (err.requestOptions.extra[ExtraKeys.needErrorToast] != false) {
      // Toast.showError(err.response?.data?.msg);
    }
    return handler.next(err);
  }

  @override
  void onRequest(
    RequestOptions options,
    RequestInterceptorHandler handler,
  ) {
    if (_loadingFunc != null) _loadingFunc!.call();
    // // 用于测试网络请求时长
    // print("****** 开始请求(Request) ******");
    // start = DateTime.now();
    if (options.extra[ExtraKeys.needLoading] != false) {
      // var loadingMsg = options.extra[ExtraKeys.needLoadingMsg];
      // _loadingFunc = Toast.showLoading(
      //   loadingMsg: loadingMsg,
      //   cancelToken: options.cancelToken,
      // );
    }
    return handler.next(options);
  }

  @override
  void onResponse(
    Response response,
    ResponseInterceptorHandler handler,
  ) {
    if (_loadingFunc != null) _loadingFunc!.call();
    // print("****** 返回请求结果(Response) ******");
    // // 用于测试网络请求时长
    // final Duration diff = DateTime.now().difference(start!);
    // print('request time : $diff');
    // 当需要toast时, 弹出提示
    if (response.requestOptions.extra[ExtraKeys.needToast] != false) {
      // Toast.showSuccess(response.data?.msg);
    }
    return handler.next(response);
  }
}
